<?php
/**
 * 搜索
 * @link https://www.leadshop.vip/
 * @copyright Copyright ©2020-2021 浙江禾成云计算有限公司
 */

namespace leadmall\api;

use leadmall\Map;
use system\api\MenusController as MenusModules;
use Yii;
use yii\web\ForbiddenHttpException;
use system\models\Menus;

class MenusController extends MenusModules implements Map
{

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['create']);
        unset($actions['index']);
        return $actions;
    }


    public function actionIndex()
    {
        return $this->actionMenus();
    }

    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $post_values = array_values($post);
        $post_keys = array_keys($post);
        $post = array_combine($post_keys, $post_values);
        $time = time();
        if (strlen($post['id'])>0) {
            $model =  Menus::findOne($post['id']);

            if (empty($model)) {
                Error('菜單不存在');
            }
            $scenarios = 'update';
            $post['updated_time'] = $time;
        } else {
            $model                =  new Menus();
            $scenarios            = 'create';
            $post['created_time'] = $time;
            $post['updated_time'] = $time;
        }
        $transaction = Yii::$app->db->beginTransaction(); //启动数据库事务
        //统一替换本地文件地址
        $post = url2str($post);

        $model->setScenario($scenarios);
        $model->setAttributes($post);
        if ($model->validate()) {
            $res = $model->save();
            if ($res) {
                $id = $model->id;
                $transaction->commit();
                return ['id' => $id];
            } else {
                $transaction->rollBack();
                Error('保存失败');
            }
        }
        return $model;
    }

}
